<?php
namespace app\manage\controller;
use think\Db;

class UserPay extends Base
{
    public function index(){
        if( request()->isAjax() ){
            $page = input('page');
            $limit = input('limit');
            $year = input('year');
            $plat = input('plat');

            $wherePay = "debug=0 && pay_result=1";
            if($plat == 'cps'){
                $wherePay .= ' && channel_id=1000';
            }else{
                $wherePay .= ' && channel_id>=5000';
            }

            $field = "channel_id, my_user_name, my_user_id, total_price";

            if($year){
                $subQuery = Db::name('PayOrderY_'.$year)
                    ->field($field)
                    ->where($wherePay)
                    ->buildSql();
            }else{
                $subQuery = Db::name('PayOrderY_2016')
                    ->field($field)
                    ->where($wherePay)
                    ->union("select {$field} from sdk_pay_order_y_2017 where ({$wherePay})", true)
                    ->union("select {$field} from sdk_pay_order_y_2018 where ({$wherePay})", true)
                    ->buildSql();
            }

            $count = Db::table($subQuery.' y')->group('my_user_id')->count();
            $select = Db::table($subQuery.' y')
                ->field('channel_id, my_user_name, my_user_id, sum(total_price)/100 as tt')
                ->order('tt desc')
                ->group('my_user_id')
                ->limit(($page-1)*$limit, $limit)
                ->select();

            $data = [];
            foreach ($select as $k=>$v){
                $data[] = [
                    'my_user_id' => $v['my_user_id'],
                    'my_user_name' => $v['my_user_name'],
                    'channel_id' => $v['channel_id']=='1000' ? 'CPS' : 'SDK',
                    'total_price' => $v['tt']
                ];
            }

            $this->layTable(0, '用户列表', $data, $count);
        }else{
            return view();
        }
    }
}